from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
from django.conf import settings
from qcloud_cos.cos_exception import CosServiceError


def create_bucket(bucket, region='ap-nanjing'):
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    region = 'ap-nanjing'  # 替换为用户的 Region
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    # 创建桶
    client.create_bucket(
        Bucket=bucket,
        ACL="public-read",
    )
    # 创建跨域设置
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['PUT', 'GET', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': '*',
                'ExposeHeader': '*',
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )


# 把文件上传到桶里面
def upload_file(bucket, region, file_object, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    # 高级上传图片
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_object,
        Key=key,
    )

    return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, region, key)


# 在cos中删除图片
def delete_file(bucket, region, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    # 高级删除图片
    response = client.delete_object(
        Bucket=bucket,
        Key=key,
    )


# 在cos中批量删除图片
def delete_file_list(bucket, region, key_list):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    objects = {
        "Quiet": "true",
        "Object": key_list
    }
    # 高级批量删除图片
    response = client.delete_objects(
        Bucket=bucket,
        Delete=objects
    )


# 获取临时凭证
def credential(bucket, region):
    from sts.sts import Sts

    config = {

        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥
        'secret_key': settings.TENCENT_COS_KEY,
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 简单上传
            # 'name/cos:PutObject',
            # 'name/cos:PostObject',
            # # 分片上传
            # 'name/cos:InitiateMultipartUpload',
            # 'name/cos:ListMultipartUploads',
            # 'name/cos:ListParts',
            # 'name/cos:UploadPart',
            # 'name/cos:CompleteMultipartUpload'
            '*'
        ],

    }

    try:
        sts = Sts(config)
        response = sts.get_credential()
        return response
    except Exception as e:
        print(e)


# 进行etag校验
def check_file(bucket, region, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    data = client.head_object(
        Bucket=bucket,
        Key=key,
    )

    return data


# 进行删除桶，删除项目时
def delete_bucket(bucket, region):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    # 进行异常处理
    try:
        # 找到所有的文件 & 删除
        while True:
            part_objects = client.list_objects(bucket)
            contents = part_objects.get('Contents')
            if not contents:
                break
            # 进行删除
            objects = {
                "Quiet": "true",
                "Object": [{'Key': item['Key']} for item in contents]
            }
            client.delete_objects(bucket, objects)
            if part_objects['IsTruncated'] == 'false':
                break
        # 找到碎片 & 删除
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            upload = part_uploads.get("Upload")
            if not upload:
                break
            for item in upload:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
            if part_uploads['IsTruncated'] == 'false':
                break
        # 最后把桶给删除掉
        client.delete_bucket(bucket)
    except CosServiceError as e:
        pass
